package SlidingWindowMaximum_239;

import java.util.Arrays;
import java.util.PriorityQueue;

public class Solution {
    public static int[] maxSlidingWindow(int[] nums, int k) {

        if (nums.length <= k) {
            int min = Integer.MIN_VALUE;
            for (int num : nums) {
                min = Math.max(min, num);
            }
            return new int[]{min};
        }

        PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1);

        int[] result = new int[nums.length - k + 1];
        int left = 0;
        int right = left + k - 1;
        while (right < nums.length) {
            if (left == 0) {
                int temp_point = 0;
                while (temp_point <= right) {
                    heap.add(nums[temp_point]);
                    temp_point++;
                }
            } else {
                heap.add(nums[right]);
            }
            Integer peek = heap.peek();
            result[left] = peek;
            if (peek == nums[left]) {
                heap.poll();
            }
            left++;
            right++;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(maxSlidingWindow(new int[]{9, 10, 9, -7, -4, -8, 2, -6}, 5)));
    }
}
